package com.example.data;

import java.util.List;

import android.content.Context;
import android.util.Log;

import com.example.application.BaseApplication;
import com.example.dao.DaoSession;
import com.example.dao.Diary;
import com.example.dao.DiaryDao;

public class CacheDiary {
	
	private static final String TAG = CacheDiary.class.getSimpleName();
	private static CacheDiary instance;
	private static Context appContext;
	private DaoSession mDaoSession;
	private DiaryDao diaryDao;
	
	
	private CacheDiary() {
	}

	public static CacheDiary getInstance(Context context) {
		if (instance == null) {
			instance = new CacheDiary();
			if (appContext == null){
				appContext = context.getApplicationContext();
			}
			instance.mDaoSession = BaseApplication.getDaoSession(context);
			instance.diaryDao = instance.mDaoSession.getDiaryDao();
		}
		return instance;
	}
	
	
	public Diary loadDiary(long id) {
		return diaryDao.load(id);
	}
	
	public List<Diary> loadAllDiary(){
		return diaryDao.loadAll();
	}
	
	public List<Diary> queryDiary(String where, String... params){
		return diaryDao.queryRaw(where, params);
	}
	
	public long saveDiary(Diary diary){
		return diaryDao.insertOrReplace(diary);
	}
	
	public void saveDiaryLists(final List<Diary> list){
	    	if(list == null || list.isEmpty()){
			     return;
		    }
	    	diaryDao.getSession().runInTx(new Runnable() {
			@Override
			public void run() {
				for(int i=0; i<list.size(); i++){
					Diary diary = list.get(i);
					diaryDao.insertOrReplace(diary);
				}
			}
		});
	}
	
	public void deleteAllDiary(){
		diaryDao.deleteAll();
	}
	
	public void deleteDiary(long id){
		diaryDao.deleteByKey(id);
		Log.i(TAG, "delete");
	}
	
	public void deleteDiary(Diary diary){
		diaryDao.delete(diary);
	}
	
}
